package draw.server.activityStatus.operate;

import draw.controller.param.DrawPrizesData;
import draw.dao.dataObject.ActivityPrizeDO;
import draw.dao.mapper.ActivityMapper;
import draw.dao.mapper.ActivityPrizeMapper;
import draw.server.dto.ActivityDto;
import draw.server.enums.ActivityStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class ActivityOperate extends AbstractOperate {

    @Autowired
    ActivityMapper activityMapper;
    @Autowired
    ActivityPrizeMapper activityPrizeMapper;

    @Override
    public int sequence() {
        return 2;
    }

    @Override
    public Boolean needConvert(DrawPrizesData param) {
        if (param == null) {
            return false;
        }

        ActivityDto activityDto = activityMapper.selectActivityById(param.getActivityId());

        if (activityDto == null) {
            log.warn("活动不存在");
            return false;
        }

        if (ActivityStatusEnum.COMPLETED.equals(activityDto.getStatus())) {
            log.warn("活动已经结束");
            return false;
        }

        //这里要看是不是所有的都被抽了
        List<ActivityPrizeDO> activityPrizeDOS = activityPrizeMapper.selectById(param.getActivityId());

        for (ActivityPrizeDO x : activityPrizeDOS) {
            //如果有一个没被抽就表示不用扭转活动状态
            if (ActivityStatusEnum.PRIZE_RUNNING.equals(x.getStatus())) {
                return false;
            }
        }

        return true;
    }

    @Override
    public Boolean convert(DrawPrizesData param) {
        if(param == null) {
            log.warn("param is null");
            return false;
        }

        try {
            activityMapper.updateStatus(param, ActivityStatusEnum.COMPLETED);
        }catch (Exception e) {
            log.error("扭转活动状态出现错误 param: {}, errorInfo:{}", param + " " + ActivityStatusEnum.COMPLETED,
                    e.getMessage());
            return false;
        }

        return true;
    }
}
